import { TreeOption } from 'naive-ui'
import { useI18n } from 'vue-i18n'

import { createRole, updateRole } from '@/apis/index'
import { getMenuAllTree } from '@/apis/menu'
import { RoleModalDto } from '@/apis/role/type/dto'
import { useRef } from '@/hooks'
import { StatusEnum } from '@/types/enum'
import { FormInputList, FormInputListRules } from '@/types/interface'
import { catchToTuple } from '@/utils'

export function useModal({ init }: any) {
  const { t } = useI18n()
  const modalShow = ref<boolean>(false)
  const modalType = ref<'create' | 'update'>('create')

  const menuTree = ref<Array<TreeOption>>([])
  // 表单数据
  const [modalFormData, handleModalFormDataReset] = useRef<RoleModalDto>({
    key: '',
    name: '',
    sort: 1,
    menu_ids: {
      checkedKeys: [],
      halfCheckedKeys: [],
    },
    status: StatusEnum.DYNAMIC,
    remark: '',
  })

  // 表单配置
  const modalFormList = computed((): FormInputList<RoleModalDto> => {
    return [
      {
        key: 'key',
        type: 'input',
        label: t('role.key'),
        placeholder: t('common.please_enter', { name: t('role.key') }),
      },
      {
        key: 'name',
        type: 'input',
        label: t('role.name'),
        placeholder: t('common.please_enter', { name: t('role.name') }),
      },
      {
        key: 'sort',
        type: 'input-number',
        label: t('common.sort'),
        placeholder: t('common.please_enter', { name: t('common.sort') }),
      },
      {
        key: 'menu_ids',
        type: 'tree',
        label: t('role.menu_ids'),
        placeholder: t('common.please_enter', { name: t('role.menu_ids') }),
        keyField: 'key',
        labelField: 'label',
        childrenField: 'children',
        data: menuTree.value,
      },
      {
        key: 'status',
        type: 'radio',
        label: t('common.status'),
        placeholder: t('common.please_select', { name: t('common.status') }),
        options: [
          { label: t('common.status_enable'), value: StatusEnum.DYNAMIC },
          { label: t('common.status_disable'), value: StatusEnum.STATIC },
        ],
      },
      {
        key: 'remark',
        type: 'textarea',
        label: t('common.remark'),
        placeholder: t('common.please_enter', { name: t('common.remark') }),
      },
    ]
  })

  // 表单校验规则
  const modalFormRules: FormInputListRules<RoleModalDto> = {
    key: {
      required: true,
      renderMessage: () => t('common.please_enter', { name: t('role.key') }),
      trigger: ['input'],
    },
    name: {
      required: true,
      renderMessage: () => t('common.please_enter', { name: t('role.name') }),
      trigger: ['input'],
    },
    sort: {
      type: 'number',
      required: true,
      renderMessage: () => t('common.please_enter', { name: t('common.sort') }),
      trigger: ['input'],
    },
    status: {
      required: true,
      renderMessage: () => t('common.please_select', { name: t('common.status') }),
      trigger: ['change'],
    },
  }

  // 取消
  const handleModalCancel = () => {
    modalShow.value = false
    handleModalFormDataReset()
  }

  // 提交
  const handleModalSubmit = async () => {
    console.log(modalFormData.value)
    const [err, data] = await catchToTuple(
      modalType.value === 'update' ? updateRole(modalFormData.value) : createRole(modalFormData.value),
    )

    if (err) return

    if (data?.code === 200) {
      window.$message.success(data.message)
      handleModalCancel()
      init()
    }
  }

  // 获取 菜单树
  const getMenuTree = async () => {
    const [err, data] = await catchToTuple(getMenuAllTree())

    if (err) return

    if (data?.code === 200 && data.data) {
      menuTree.value = data.data
    }
  }
  onMounted(() => {
    getMenuTree()
  })

  return {
    modalShow,
    modalType,
    modalFormData,
    modalFormList,
    modalFormRules,
    handleModalCancel,
    handleModalSubmit,
    handleModalFormDataReset,
  }
}
